package com.michale.framework.security.context;

import com.alibaba.fastjson2.JSON;
import com.michale.common.result.AjaxResult;
import com.michale.common.utils.Ip.ServletUtils;
import com.michale.common.utils.String.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author Michale
 * @apiNote 权限校验失败
 */
@Component
public class AuthenticationDenied implements AccessDeniedHandler, Serializable {

    private static final long serialVersionUID = 6397846940288115264L;

    /**
     * 在用户权限校验失败时调用
     *
     * @param request       request请求域
     * @param response      response响应
     * @param accessDeniedException 身份验证异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //获取禁止 授权状态码
        int code = HttpStatus.FORBIDDEN.value();
        //将字符串渲染到客户端
        String msg = StringUtils.format("请求访问：{}，访问受限，授权过期", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
